package com.zja.www.view;

import com.zja.www.controller.AdminController;
import com.zja.www.controller.BaseController;
import com.zja.www.entity.Department;
import com.zja.www.entity.Doctor;
import com.zja.www.entity.Schedule;
import com.zja.www.entity.User;
import com.zja.www.service.*;
import com.zja.www.service.DepartmentService;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Scanner;

public class AdminView extends BaseController {
    private final AdminController adminController;
    private final AdminService adminService;
    private final DepartmentService departmentService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public AdminView(AdminController adminController,
                     AdminService adminService,
                     UserService userService,
                     DoctorService doctorService,
                     MedicalRecordService medicalRecordService,
                     DepartmentService departmentService) {
        super(userService, doctorService, medicalRecordService);
        this.adminController = adminController;
        this.adminService = adminService;
        this.departmentService = departmentService;
    }

    public void showAdminMenu(AdminView adminView) {
        while (true) {
            System.out.println("\n================管理员界面=======================");
            System.out.println("1.登录");
            System.out.println("0.返回主菜单");
            System.out.print("请选择：");

            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {
                case 1:
                    adminView.showAdminLoginMenu();  // 显示管理员登录界面
                    break;
                case 0:
                    return;  // 返回主菜单
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    /**
     * 显示管理员登录界面
     */
    public void showAdminLoginMenu() {
        System.out.println("\n================管理员登录界面===================");
        System.out.print("请输入您的姓名：");
        String username = readStringInput();
        System.out.print("请输入您的密码：");
        String password = readStringInput();

        if (adminController.login(username, password)) {
            System.out.println("登录成功！");
            showAdminMainMenu();
        } else {
            System.out.println("登录失败，用户名或密码错误！");
        }
    }

    /**
     * 显示管理员主菜单
     */
    public void showAdminMainMenu() {
        while (true) {
            System.out.println("\n===================管理员界面====================");
            System.out.println("1.查询排班信息");
            System.out.println("2.添加新排班");
            System.out.println("3.修改现有排班");
            System.out.println("4.删除排班");
            System.out.println("5.用户身份认证");
            System.out.println("6.科室管理");
            System.out.println("0.返回主菜单");
            System.out.print("请输入您的选择：");

            int choice = readIntInput();
            switch (choice) {
                case 1:
                    showScheduleQueryMenu();
                    break;
                case 2:
                    addNewSchedule();
                    break;
                case 3:
                    modifySchedule();
                    break;
                case 4:
                    deleteSchedule();
                    break;
                case 5:
                    showUserVerificationMenu();
                    break;
                case 6:
                    showDepartmentManagementMenu();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    /**
     * 显示排班查询菜单
     */
    private void showScheduleQueryMenu() {
        while (true) {
            System.out.println("\n============排班查询菜单============");
            System.out.println("1.按日期查询");
            System.out.println("2.按医生查询");
            System.out.println("3.按科室查询");
            System.out.println("0.返回上级菜单");
            System.out.print("选择查询方式：");

            int choice = readIntInput();
            switch (choice) {
                case 1:
                    queryByDate();
                    break;
                case 2:
                    queryByDoctor();
                    break;
                case 3:
                    queryByDepartment();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    /**
     * 显示科室管理菜单
     */
    private void showDepartmentManagementMenu() {
        while (true) {
            System.out.println("\n============科室信息管理============");
            System.out.println("1.添加科室");
            System.out.println("2.修改科室信息");
            System.out.println("3.删除科室");
            System.out.println("4.查询所有科室");
            System.out.println("0.返回上级菜单");
            System.out.print("请选择操作：");

            int choice = readIntInput();
            switch (choice) {
                case 1:
                    addDepartment();
                    break;
                case 2:
                    modifyDepartment();
                    break;
                case 3:
                    deleteDepartment();
                    break;
                case 4:
                    listAllDepartments();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    /**
     * 添加科室
     */
    private void addDepartment() {
        System.out.println("\n============添加科室=============");
        System.out.print("请输入科室名称: ");
        String name = readStringInput();

        System.out.print("请输入科室简介: ");
        String description = readStringInput();

        Department department = new Department(0, name, description);

        if (departmentService.addDepartment(department)) {
            System.out.println("科室添加成功！");
        } else {
            System.out.println("科室添加失败！");
        }
    }

    /**
     * 修改科室信息
     */
    private void modifyDepartment() {
        System.out.println("\n============修改科室信息=============");
        System.out.print("请输入要修改的科室ID: ");
        int deptId = readIntInput();

        Department department = departmentService.getDepartmentById(deptId);
        if (department == null) {
            System.out.println("科室不存在！");
            return;
        }

        System.out.println("当前科室信息:");
        System.out.println("ID: " + department.getId());
        System.out.println("名称: " + department.getName());
        System.out.println("简介: " + department.getDescription());

        System.out.println("请输入新的信息(留空表示不修改):");

        System.out.print("新名称: ");
        String newName = readStringInput();

        System.out.print("新简介: ");
        String newDesc = readStringInput();

        if (!newName.isEmpty()) department.setName(newName);
        if (!newDesc.isEmpty()) department.setDescription(newDesc);

        if (departmentService.updateDepartment(department)) {
            System.out.println("科室信息修改成功！");
        } else {
            System.out.println("科室信息修改失败！");
        }
    }

    /**
     * 删除科室
     */
    private void deleteDepartment() {
        System.out.println("\n============删除科室=============");
        System.out.print("请输入要删除的科室ID: ");
        int deptId = readIntInput();

        Department department = departmentService.getDepartmentById(deptId);
        if (department == null) {
            System.out.println("科室不存在！");
            return;
        }

        System.out.println("将删除以下科室:");
        System.out.println("ID: " + department.getId());
        System.out.println("名称: " + department.getName());

        System.out.print("确定要删除此科室吗?(Y/N): ");
        String confirm = readStringInput();
        if ("Y".equalsIgnoreCase(confirm)) {
            if (departmentService.deleteDepartment(deptId)) {
                System.out.println("科室删除成功！");
            } else {
                System.out.println("科室删除失败！");
            }
        } else {
            System.out.println("已取消删除操作");
        }
    }

    /**
     * 列出所有科室
     */
    private void listAllDepartments() {
        System.out.println("\n============所有科室列表=============");
        List<Department> departments = departmentService.getAllDepartments(); // 使用departmentService

        if (departments.isEmpty()) {
            System.out.println("没有科室记录！");
            return;
        }

        System.out.println("\n======= 科室列表 =======");
        System.out.printf("%-5s%-15s%-30s%n",
                "ID", "名称", "简介");

        for (Department d : departments) {
            System.out.printf("%-5d%-15s%-30s%n",
                    d.getId(),
                    d.getName(),
                    d.getDescription());
        }
    }

    /**
     * 添加新排班
     */
    private void addNewSchedule() {
        System.out.println("\n============添加新排班=============");
        System.out.print("请输入医生ID: ");
        int doctorId = readIntInput();

        Doctor doctor = doctorService.getDoctorById(doctorId);
        if (doctor == null) {
            System.out.println("医生不存在！");
            return;
        }

        System.out.print("请输入日期(YYYY-MM-DD): ");
        String dateStr = readStringInput();

        System.out.print("请输入开始时间(HH:mm): ");
        String startTime = readStringInput();

        System.out.print("请输入结束时间(HH:mm): ");
        String endTime = readStringInput();

        System.out.print("请输入最大预约数: ");
        int maxAppointments = readIntInput();

        try {
            Timestamp date = new Timestamp(dateFormat.parse(dateStr).getTime());
            Schedule schedule = new Schedule(0, doctorId, date, startTime, endTime, maxAppointments, 0);

            if (adminService.addSchedule(schedule)) {
                System.out.println("排班添加成功！");
            } else {
                System.out.println("排班添加失败！");
            }
        } catch (ParseException e) {
            System.out.println("日期格式错误！");
        }
    }

    /**
     * 修改现有排班
     */
    private void modifySchedule() {
        System.out.println("\n============修改排班=============");
        System.out.print("请输入要修改的排班ID: ");
        int scheduleId = readIntInput();

        Schedule schedule = adminService.getScheduleById(scheduleId);
        if (schedule == null) {
            System.out.println("排班不存在！");
            return;
        }

        System.out.println("当前排班信息:");
        System.out.println("医生ID: " + schedule.getDoctorId());
        System.out.println("日期: " + dateFormat.format(schedule.getDate()));
        System.out.println("时间段: " + schedule.getStartTime() + "-" + schedule.getEndTime());
        System.out.println("最大预约数: " + schedule.getMaxAppointments());


        System.out.println("请输入新的信息(留空表示不修改):");
        System.out.print("新日期(YYYY-MM-DD): ");
        String newDateStr = readStringInput();

        System.out.print("新开始时间(HH:mm): ");
        String newStartTime = readStringInput();

        System.out.print("新结束时间(HH:mm): ");
        String newEndTime = readStringInput();

        System.out.print("新最大预约数: ");
        String maxAppointmentsInput = readStringInput();

        try {
            if (!newDateStr.isEmpty()) {
                schedule.setDate(new Timestamp(dateFormat.parse(newDateStr).getTime()));
            }
            if (!newStartTime.isEmpty()) {
                schedule.setStartTime(newStartTime);
            }
            if (!newEndTime.isEmpty()) {
                schedule.setEndTime(newEndTime);
            }
            if (!maxAppointmentsInput.isEmpty()) {
                schedule.setMaxAppointments(Integer.parseInt(maxAppointmentsInput));
            }

            if (adminService.updateSchedule(schedule)) {
                System.out.println("排班修改成功！");
            } else {
                System.out.println("排班修改失败！");
            }
        } catch (ParseException e) {
            System.out.println("日期格式错误！");
        }
    }

    /**
     * 删除排班
     */
    private void deleteSchedule() {
        System.out.println("\n============删除排班=============");
        System.out.print("请输入要删除的排班ID: ");
        int scheduleId = readIntInput();

        Schedule schedule = adminService.getScheduleById(scheduleId);
        if (schedule == null) {
            System.out.println("排班不存在！");
            return;
        }

        System.out.println("将删除以下排班:");
        System.out.println("医生ID: " + schedule.getDoctorId());
        System.out.println("日期: " + dateFormat.format(schedule.getDate()));
        System.out.println("时间段: " + schedule.getStartTime() + "-" + schedule.getEndTime());

        System.out.print("确定要删除此排班吗?(Y/N): ");
        String confirm = readStringInput();
        if ("Y".equalsIgnoreCase(confirm)) {
            if (adminService.deleteSchedule(scheduleId)) {
                System.out.println("排班删除成功！");
            } else {
                System.out.println("排班删除失败！");
            }
        } else {
            System.out.println("已取消删除操作");
        }
    }

    /**
     * 按日期查询排班
     */
    private void queryByDate() {
        System.out.println("\n============日期查询=============");
        System.out.print("请输入日期(YYYY-MM-DD): ");
        String dateStr = readStringInput();

        try {
            Timestamp date = new Timestamp(dateFormat.parse(dateStr).getTime());
            List<Schedule> schedules = adminService.getSchedulesByDate(date);

            if (schedules.isEmpty()) {
                System.out.println("该日期没有排班！");
                return;
            }

            System.out.println("\n======= 排班信息 =======");
            System.out.printf("%-8s%-12s%-15s%-15s%-8s%-8s\n",
                    "ID", "医生ID", "日期", "时间段", "最大数", "已预约");

            for (Schedule s : schedules) {
                System.out.printf("%-8d%-12d%-15s%-15s%-8d%-8d\n",
                        s.getId(),
                        s.getDoctorId(),
                        dateFormat.format(s.getDate()),
                        s.getStartTime() + "-" + s.getEndTime(),
                        s.getMaxAppointments(),
                        s.getBookedAppointments());
            }
        } catch (ParseException e) {
            System.out.println("日期格式错误！");
        }
    }

    /**
     * 按医生查询排班
     */
    private void queryByDoctor() {
        System.out.println("\n============医生查询===============");

        System.out.print("请输入医生ID: ");
        int doctorId = readIntInput();

        List<Schedule> schedules = adminService.getSchedulesByDoctor(doctorId);

        if (schedules.isEmpty()) {
            System.out.println("该医生没有排班记录！");
            return;
        }

        System.out.println("\n======= 排班信息 =======");
        System.out.printf("%-8s%-15s%-15s%-8s%-8s\n",
                "ID", "日期", "时间段", "最大数", "已预约");

        for (Schedule s : schedules) {
            System.out.printf("%-8d%-15s%-15s%-8d%-8d\n",
                    s.getId(),
                    dateFormat.format(s.getDate()),
                    s.getStartTime() + "-" + s.getEndTime(),
                    s.getMaxAppointments(),
                    s.getBookedAppointments());
        }
    }

    /**
     * 按科室查询排班
     */
    private void queryByDepartment() {
        System.out.println("\n=============科室查询================");
        System.out.print("请输入科室ID: ");
        int departmentId = readIntInput();

        List<Schedule> schedules = adminService.getSchedulesByDepartment(departmentId);

        if (schedules.isEmpty()) {
            System.out.println("该科室没有排班记录！");
            return;
        }

        System.out.println("\n======= 排班信息 =======");
        System.out.printf("%-8s%-12s%-15s%-15s%-8s%-8s\n",
                "ID", "医生ID", "日期", "时间段", "最大数", "已预约");

        for (Schedule s : schedules) {
            System.out.printf("%-8d%-12d%-15s%-15s%-8d%-8d\n",
                    s.getId(),
                    s.getDoctorId(),
                    dateFormat.format(s.getDate()),
                    s.getStartTime() + "-" + s.getEndTime(),
                    s.getMaxAppointments(),
                    s.getBookedAppointments());
        }
    }

    /**
     * 显示用户身份认证菜单
     */
    private void showUserVerificationMenu() {
        while (true) {
            System.out.println("\n==========用户身份认证界面===========");
            System.out.println("1.未认证学生");
            System.out.println("2.已认证学生");
            System.out.println("0.返回上级菜单");
            System.out.print("请选择：");

            int choice = readIntInput();
            switch (choice) {
                case 1:
                    showUnverifiedStudents();
                    break;
                case 2:
                    showVerifiedStudents();
                    break;
                case 0:
                    return;
                default:
                    System.out.println("输入无效，请重新选择！");
            }
        }
    }

    /**
     * 显示未认证学生列表
     */
    private void showUnverifiedStudents() {
        System.out.println("\n==========未认证学生界面==========");
        List<User> unverifiedUsers = adminService.getUnverifiedUsers();

        if (unverifiedUsers.isEmpty()) {
            System.out.println("没有待认证的学生！");
            return;
        }

        System.out.println("\n======= 未认证学生列表 =======");
        System.out.printf("%-4s%-15s%n", "ID", "用户名");

        for (User user : unverifiedUsers) {
            System.out.printf("%-4d%-15s%n",
                    user.getId(),
                    user.getUserName()
                    );
        }

        System.out.print("\n请输入学生ID通过验证/0.返回: ");
        int userId = readIntInput();
        if (userId != 0) {
            if (adminService.verifyUser(userId)) {
                System.out.println("学生认证成功！");
            } else {
                System.out.println("学生认证失败！");
            }

        }
    }

    /**
     * 显示已认证学生列表
     */
    private void showVerifiedStudents() {
        System.out.println("\n===========已认证学生界面=============");
        List<User> verifiedUsers = adminService.getVerifiedUsers();

        if (verifiedUsers.isEmpty()) {
            System.out.println("没有已认证的学生！");
            return;
        }

        System.out.println("\n======= 已认证学生列表 =======");
        System.out.printf("%-4s%-15s%n", "ID", "用户名");

        for (User user : verifiedUsers) {
            System.out.printf("%-4d%-15s\n",
                    user.getId(),
                    user.getUserName()
                   );
        }

        System.out.print("\n请输入学生ID取消验证/0.返回: ");
        int userId = readIntInput();
        if (userId != 0) {
            if (adminService.unverifyUser(userId)) {
                System.out.println("学生取消认证成功！");
            } else {
                System.out.println("学生取消认证失败！");
            }
        }

    }
}
